const doRequest = require("./signer.js");
const code = require("./code.js");

// 根据fileID,获取图片地址
const getTempFileURL = async (arr) => {
	const {
		fileList
	} = await uniCloud.getTempFileURL({
		fileList: arr,
	});
	return fileList;
};

// 把 base64 转成 ArrayBuffer
function base64ToArrayBuffer(base64) {
	return Buffer.from(base64, 'base64');
	// const binaryString = atob(base64);
	// const len = binaryString.length;
	// const bytes = new Uint8Array(len);
	// for (let i = 0; i < len; i++) {
	// 	bytes[i] = binaryString.charCodeAt(i);
	// }
	// return bytes.buffer;
}

module.exports = {
	async getFileURL(arr) {
		const {
			fileList
		} = await uniCloud.getTempFileURL({
			fileList: arr,
		});
		return fileList;
	},

	// ai绘图
	async aiDrawing(val) {
		const collection = uniCloud.database().collection("AIMenuList");
		const {
			data
		} = await collection.doc(val.id).get();
		const params = {
			data: {
				...data[0].data,
				...val.data,
			},
			query: data[0].query,
			contentType: data[0].contentType,
		};
		// 2022版本图片以数组传入
		if (data[0].query.Version === "2022-08-31") {
			params.data.image_urls = [val.imgurl];
			val.merge_infos && params.data.image_urls.push(val.merge_infos)
		} else {
			params.data.image_url = val.imgurl
		}
		const res = await doRequest(params);
		if (res.status === 200) {
			const arrayBuffer =
				data[0].query.Version === "2022-08-31" ?
				base64ToArrayBuffer(res.data.data.binary_data_base64[0]) :
				base64ToArrayBuffer(res.data.data.image);
			const {
				fileID
			} = await uniCloud.uploadFile({
				cloudPathAsRealPath: true,
				cloudPath: `user-images/${Date.now()}_${Math.floor(
          Math.random() * 900 + 100
        )}.png`,
				fileContent: arrayBuffer,
			});
			const filePathList = await getTempFileURL([fileID]);
			return {
				code: 200,
				data: {
					fileid: fileID,
					imgurl: filePathList[0].tempFileURL,
				},
			};
		} else {
			return {
				code: 400,
				message: code[res.data.code],
			};
		}
	},
};